package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import static com.itheima.constant.MessageConstant.QUERY_CHECKITEM_FAIL;

@RestController
@RequestMapping("checkItem")
public class CheckItemController {
    @Reference(version = "1.0")
    CheckItemService checkItemService;

    @Autowired
    JedisPool jedisPool;

    @PostMapping("findPage")
    @PreAuthorize("hasAnyAuthority('CHECKITEM_QUERY')")
    public Result findPage(@RequestBody QueryPageBean queryPageBean) {
        return checkItemService.findPage(queryPageBean);
    }

    @GetMapping("findAll")
    @PreAuthorize("hasAnyAuthority('CHECKITEM_QUERY')")
    public Result findAll() {
        //使用redis优化
        //如果缓存中有,调用缓存中的数据,如果没有,调用dubbo服务
        try (Jedis jedis = jedisPool.getResource()) {
            String checkitemAll = jedis.get("checkitem_all");
            if (StringUtils.isNotBlank(checkitemAll)) {
                return JSON.parseObject(checkitemAll, Result.class);
            }
            Result all = checkItemService.findAll();
            jedis.setex("checkitem_all",5*60, JSON.toJSONString(all));
            //设置过期时间
            return all;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(500, QUERY_CHECKITEM_FAIL);
    }

    @PostMapping("save")
    @PreAuthorize("hasAnyAuthority('CHECKITEM_ADD')")
    public Result save(@RequestBody CheckItem checkItem) {
        return checkItemService.save(checkItem);
    }

    @PostMapping("update")
    @PreAuthorize("hasAnyAuthority('CHECKITEM_EDIT')")
    public Result update(@RequestBody CheckItem checkItem) {
        return checkItemService.update(checkItem);
    }

    @GetMapping("findById/{id}")
    @PreAuthorize("hasAnyAuthority('CHECKITEM_QUERY')")
    public Result findById(@PathVariable("id") Integer id) {
        return checkItemService.findById(id);
    }

    @GetMapping("delete/{id}")
    @PreAuthorize("hasAnyAuthority('CHECKITEM_DELETE')")
    public Result delete(@PathVariable("id") Integer id) {
        return checkItemService.delete(id);
    }
}
